<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Http\Route;


use Application\TBK\Controller\GoodsController;
use Selibra\Config\Config;
use Selibra\Tools\Console;

class RouterMapper
{


    /**
     * 路由映射
     * @var array
     */
    private static array $routerMapper = [];


    /**
     * 带有预定义参数的路由映射
     * @var array
     */
    private static array $preParmasRouterMapper = [];


    /**
     * @param RouterConfig $config
     */
    public static function createRoute(RouterConfig $config)
    {
        if (!empty($config->getParams())) {
            // 带有预定义参数
            self::$preParmasRouterMapper[strtolower($config->getType())][strtolower($config->getAlias())][(string)$config->getVersion()] = [
                'alias' => $config->getAlias(),
                'mapper' => $config->getClass(),
                'method' => $config->getMethod(),
                'params' => $config->getParams()
            ];
        } else {
            self::$routerMapper[strtolower($config->getType())][strtolower($config->getAlias())][(string)$config->getVersion()] = [
                'mapper' => $config->getClass(),
                'method' => $config->getMethod(),
            ];
        }

    }


    /**
     * @param $route
     * @param $type
     * @return array|null
     */
    public static function getRouterMapper($route, $type)
    {
        if (empty(self::$routerMapper[strtolower($type)]) || !array_key_exists(strtolower($route), self::$routerMapper[strtolower($type)])) {
            // 读取预定义参数的路由
            $routeArray = explode('/', $route);
            foreach ($routeArray as $key => $item) {
                $routeKey = implode('/', array_slice($routeArray, 0, $key + 1));
                if (!empty(self::$preParmasRouterMapper[strtolower($type)]) && !empty(self::$preParmasRouterMapper[strtolower($type)][strtolower($routeKey)])) {
                    return self::$preParmasRouterMapper[strtolower($type)][strtolower($routeKey)];
                }
            }
            return [];
        }
        return self::$routerMapper[strtolower($type)][strtolower($route)] ?: [];
    }


}
